document.addEventListener('DOMContentLoaded', function() {
    const registerForm = document.getElementById('registerForm');
    const backBtn = document.getElementById('backBtn');
    const modal = document.getElementById('modal');
    const closeModal = document.getElementById('closeModal');

    registerForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        // 验证密码是否匹配
        if (password !== confirmPassword) {
            alert('两次输入的密码不一致！');
            return;
        }

        // 发送注册请求
        fetch('http://localhost:8888/user/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                uname: username,
                upassword: password
            })
        })
        .then(response => response.json())
        .then(data => {
            console.log(data);
            if(data.result) {
                document.getElementById('workId').textContent = data.uid;
                modal.style.display = 'block';
            } else {
                alert('注册失败: ' + (data.error || '未知错误'));
            }
        })
        .catch(error => {
            console.error('注册错误:', error);
            alert('注册出错,请稍后重试!');
        });
    });

    // 返回登录页面
    backBtn.addEventListener('click', function() {
        window.location.href = 'index.html';
    });

    // 关闭弹窗并跳转到登录页面
    closeModal.addEventListener('click', function() {
        modal.style.display = 'none';
        window.location.href = 'index.html';
    });
});
